﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Casamiel.API.Application.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V1
{
	/// <summary>
	/// 
	/// </summary>
	[ApiVersion("1.0")]
	[Produces("application/json")]
	[Route("api/v{api-version:apiVersion}/[controller]")]
	public class ICController : Controller
    {
		private string appkey = "";
		private string signKey = "";
		private string token = "";
		private readonly IcServiceSettings _settings;
		public ICController(IOptionsSnapshot<IcServiceSettings> settings){
			appkey = _settings.appKey;
			signKey = _settings.signKey;
			token = _settings.token;
		}
		[HttpPost]
		[Route("[Action]")]
		public IActionResult CardReplacement(string token,string sign,string content)
		{
			var _sc = new SimpleStringCypher(appkey);
			 string _content= _sc.Decrypt(content);
			var psigndata = Sign("token" + token + "content" + _content, signKey, signKey);
			if (psigndata != sign)
			{

				return Ok(new { code = 999, msg = "" });
			}
			//var _sc = new SimpleStringCypher(appkey);
			//var _content = _sc.Encrypt(content);
			//string signData = Sign("token" + token + "content" + content, signKey, signKey);
			return Ok();
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="token"></param>
		/// <param name="sign"></param>
		/// <param name="content"></param>
		/// <returns></returns>
		[HttpPost]
		[Route("[Action]")]
		public IActionResult TestCardReplacement(string token, string sign, string content)
		{
			
			var _sc = new SimpleStringCypher(appkey);
			string _content = _sc.Decrypt(content);
			var psigndata = Sign("token" + token + "content" + _content, signKey, signKey);
			if (psigndata != sign)
			{

				return Ok(new { code = 999, msg = "" });
			}
			//var _sc = new SimpleStringCypher(appkey);
			//var _content = _sc.Encrypt(content);
			//string signData = Sign("token" + token + "content" + content, signKey, signKey);
			return Ok();
		}

		/// <summary>
		/// 签名字符串
		/// </summary>
		/// <param name="prestr">需要签名的字符串</param>
		/// <param name="keyPre">密钥：前置密钥</param>
		/// <param name="keyAfter">密钥：后置密钥</param>
		/// <param name="_input_charset">编码格式</param>
		/// <returns>签名结果</returns>
		public static string Sign(string prestr, string keyPre, string keyAfter, string _input_charset = "utf-8")
		{
			StringBuilder sb = new StringBuilder(32);

			prestr = keyPre + prestr + keyAfter;

			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(prestr));
			for (int i = 0; i < t.Length; i++)
			{
				sb.Append(t[i].ToString("x").PadLeft(2, '0'));
			}
			return sb.ToString();
		}
	}
}
